<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Auth;
use Gate;


class AuthenticateAdmin
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  string|null  $guard
     * @return mixed
     */
    public function handle($request, Closure $next, $guard = null)
    {
        //登陆失效验证
        if (Auth::guard('admin')->guest()) {
            if ($request->wantsJson()) {
                return response()->json(['code'=>-10000,'msg'=>'登陆失效,请刷新页面']);
            } else {
                return redirect()->guest('/login');
            }
        }

        $user = Auth::guard('admin')->user();

        //令牌时间已过期,手动强制退出
        //虽然令牌的cookie有效期是5年,登录的时间是定值,根据登录时间,手动设置的过期时间强制用户本地cookie过期
        if (time()>$user->expireRememberTokenTime) {
            Auth::guard('admin')->logout();
            $request->session()->flush();
            $request->session()->regenerate();
            if ($request->wantsJson()){
                return response(['code'=>1,'msg'=>'登录已失效,请刷新页面重新登录']);
            }else{
                return redirect()->guest('/login');
            }
            
        }

        //超级管理员跳过权限验证
        if($user->masterIs){
            return $next($request);
        }
        $urlPre = 'admin';
        $urlPath = $request->path();
        $pathArr = explode('/', $urlPath );
        //请求白名单
        $white = ['/'];
        //白名单所有人都有该权限
        if (in_array($urlPath, $white)) {
            return $next($request);
        }

        //执行动作列表
        $actionPre = ['view','create','update','delete'];
        //释放地址标记
        $unsetFlog = false;
        //去除地址多余参数
        foreach ($pathArr as $key => $path) {
            if($unsetFlog){
                unset($pathArr[$key]);
            }
            if(in_array($path, $actionPre)){
                $unsetFlog = true;
            }
        }

        //动作前缀,默认全局有权限
        if (count($pathArr)==1 && in_array($pathArr[0], $actionPre)) {
            return $next($request);
        }

        $path = implode('/',$pathArr);

        //若地址未有动作,默认给查看动作
        if(!$unsetFlog){
            $path .='/'.$actionPre[0];
        }

        //用户权限验证
        if (Gate::forUser($user)->denies($path)) {
            if ($request->wantsJson()) {
                return response()->json(['code'=>1,'msg'=>'您没有权限执行此操作']);
            } else {
                return response()->view('errors.403');
            }
        }

        return $next($request);
    }
}
